
#include <assert.h>
#include <stdio.h>

#include "loger.hpp"
#include "stdout_loger.hpp"
#include "single_file_loger.hpp"
#include "chunk_file_loger.hpp"
#include "roll_file_loger.hpp"

namespace lxz
{

    loger::loger()
        : loger_(nullptr)
    {
    }

    loger::~loger()
    {
        if (loger_)
        {
            delete loger_;
            loger_ = nullptr;
        }
    }

    loger *loger::getInstance(void)
    {
        static loger v;
        return &v;
    }

    int32_t loger::init(log_level level, log_type type, const char *file)
    {
        int32_t ret = -1;
        if (type == LOG_TYPE_SINGLE_FILE)
        {
            loger_ = new single_file_loger;
            ret = dynamic_cast<single_file_loger *>(loger_)->init(level, file);
        }
        else if (type == LOG_TYPE_CHUNK_FILE)
        {
            loger_ = new chunk_file_loger;
            ret = dynamic_cast<chunk_file_loger *>(loger_)->init(level, file);
        }
        else if (type == LOG_TYPE_ROLL_FILE)
        {
            loger_ = new roll_file_loger;
            ret = dynamic_cast<roll_file_loger *>(loger_)->init(level, file);
        }
        else if (type == LOG_TYPE_STDOUT)
        {
            loger_ = new stdout_loger;
            ret = dynamic_cast<stdout_loger *>(loger_)->init(level, nullptr);
        }

        return ret;
    }

    int32_t loger::append(log_level level, const std::string &log)
    {
        if (!loger_)
        {
            fprintf(stderr, "%s", log.c_str());
            return -1;
        }

        if (level < loger_->get_level())
        {
            return -1;
        }

        loger_->append(level, log);

        return 0;
    }

} // namespace lxz